//UserServlet.java
package com.ylaihui.web;

import com.google.gson.Gson;
import com.ylaihui.pojo.User;
import com.ylaihui.service.UserService;
import com.ylaihui.service.impl.UserServiceImpl;
import com.ylaihui.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();


    /**
     * 添加 Ajax 异步请求，验证用户名是否可注册
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        boolean b = userService.existsUsername(username);

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("existsUsername", b);

        Gson gson = new Gson();
        String s = gson.toJson(stringObjectHashMap);

        resp.getWriter().write(s);
    }


        protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //System.out.println("login");
        // 获取请求参数
        //String username = req.getParameter("username");
        //String password = req.getParameter("password");
        // 使用 commons-beanutils-1.8.0.jar 中的工具类 BeanUtils.populate
        User user = WebUtils.copyMapToBean(req.getParameterMap(), new User());

        // 查询数据库中是否存在用户
        User login = userService.login(user);
        if (login == null) {
            System.out.println("登录失败");
            // 错误信息回显，将信息发送给 login.jsp
            req.setAttribute("username", user.getUsername());
            req.setAttribute("msg", "用户名或密码错误！");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            System.out.println("登录成功");

            // 设置用户登录后的用户名，将其保存在session域中
            req.getSession().setAttribute("user", user.getUsername());
            req.getSession().setAttribute("userObj", login);


            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }
    }

    /**
     * 注销
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 让session失效， 清除了用户的登录信息
        req.getSession().invalidate();
        // 2. 返回到首页
        resp.sendRedirect(req.getContextPath());
    }

    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取 session 中的谷歌验证码，
        String sessionCode = (String)req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        req.getSession().invalidate();

        //System.out.println("regist");
        // 获取请求参数
        //String username = req.getParameter("username");
        //String password = req.getParameter("password");
        //String email = req.getParameter("email");
        String code = req.getParameter("code");

        User user = WebUtils.copyMapToBean(req.getParameterMap(), new User());

        // 校验验证码
        if (sessionCode != null && sessionCode.equalsIgnoreCase(code)) {
            // 检查用户名是否存在
            boolean b = userService.existsUsername(user.getUsername());
            if (b == true) {
                // 用户名已经存在,回显信息
                req.setAttribute("msg", "用户名已经存在");
                req.setAttribute("username", user.getUsername());
                req.setAttribute("email", user.getEmail());

                // 用户名已经存在
                System.out.println("用户名不可用" + user.getUsername());
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            } else {
                userService.registUser(user);
                // 注册成功， 请求转发到 注册成功页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        } else {
            // 验证码错误，回显信息
            req.setAttribute("msg", "验证码错误");
            req.setAttribute("username", user.getUsername());
            req.setAttribute("email", user.getEmail());

            // 验证码输入错误，请求转发到 注册页面
            System.out.println("验证码错误 " + code);
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }
}
